// pages/my/my.js
var app = getApp(); //获取应用实例
const quote = app.globalData.quote;
const mta = quote.mta;
const util = quote.util;
const tools = quote.tools;
const api = quote.api;
const paths = quote.paths;
const localData = quote.localData;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        paths: paths,
        userInfo: {},
        loginStatus: false,
        videoUrl: null,
        dateTime: "",
        todayDate: "",
        LearningDays: 0,
        PracticeCounts: 0,
        PointPraiseCounts: 0,
        recordList: null,
        loadingHidden: false,
        ContinueSignData: null, //连续签到数据
        animationRedPaper: '',
        animationData: '',
        hideModal: true,
        hidemodal: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

        var self = this

        mta.Page.init();

        //检验授权
        // app.checkImpower()

        self.setData({
            userInfo: app.globalData.userInfo,
            loginStatus: app.globalData.loginStatus,
            videoUrl: app.globalData.videoUrl,
        })

        var nowDate = new Date();
        var month = nowDate.getMonth() + 1
        var str = nowDate.getFullYear() + "-" + month + "-" + nowDate.getDate();
        console.log(str)
        self.setData({
            dateTime: str,
            todayDate: str,
        })

    },
    onReady: function() {
        var that = this;


    },
    onShow: function(options) {
        var self = this

        self.setData({
            userInfo: app.globalData.userInfo,
            loginStatus: app.globalData.loginStatus,
        })

        if (app.globalData.loginStatus) {

            //获取当前日期数据
            var dataDic = {
                OpenId: app.globalData.openId,
                DateTime: self.data.dateTime,
            };

            self.requestRecordData(dataDic, function() {
                self.setData({
                    loadingHidden: true
                })
            })
        } else {
            self.setData({
                LearningDays: "0",
                PracticeCounts: "0",
                PointPraiseCounts: "0",
                loadingHidden: true
            })
        }

        self.GetSmallProgramUserContinueSignDays();
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function(params) {
        var that = this;

        if (!app.globalData.loginStatus) {
            //数据加载完后停止刷新
            setTimeout(() => {
                console.log('停止刷新');
                wx.stopPullDownRefresh();
            }, 1000);
            return
        }
        that.requestRecordData({
            OpenId: app.globalData.openId,
            DateTime: that.data.dateTime,
        }, function(params) {
            //数据加载完后停止刷新
            setTimeout(() => {
                console.log('停止刷新');
                wx.stopPullDownRefresh();
            }, 1000);
        })

    },
    popSigninRule(e) { //弹出签到规则
        var that = this;

        console.log('点击弹出签到规则', e)
        var stamp = e.currentTarget.dataset.stamp;

        that.setData({
            hideModal: false
        })

        app.aldstat.sendEvent('我的-口语-点击签到规则', { 'stamp': stamp });
        mta.Event.stat("my_spoken_clickPopSigninRule", { 'stamp': stamp });
    },
    closeRule() { //关闭规则
        var that = this;

        that.setData({
            hideModal: true
        })
    },
    GetSmallProgramUserContinueSignDays() { //获取用户连续签到的天数 
        var that = this;

        var dataDic = {
            OpenId: app.globalData.openId
        };

        api.methodGetSmallProgramUserContinueSignDays({
            dataDic,
            success: function(res) {
                console.log(res);
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    //刷新当前界面数据
                    var data = res.data.data;
                    var ContinueSignData = data.ContinueSignData; //localData.signData
                    var length = ContinueSignData.length;
                    var sortContinueSignData = []; //排序后的数据
                    for (let i = 0; i < length; i++) { //按照日期排序
                        const ele = ContinueSignData[i];
                        for (let j = 1; j < length + 1; j++) {
                            if (ele.Days == j) {
                                sortContinueSignData[j - 1] = ele
                            }
                        }
                    }
                    console.log('排序后的数据', sortContinueSignData)
                    that.setData({
                        ContinueSignDays: data.ContinueSignDays, //sortContinueSignData
                        ContinueSignData: sortContinueSignData //localData.ContinueSignData
                    });
                    app.aldstat.sendEvent('我的-口语-签到', { '连续签到': data.ContinueSignDays });
                    mta.Event.stat("my_spoken_clicksignin", { 'pointpraisecounts': data.ContinueSignDays });
                    console.log(data)
                }
            },
            fail: (res) => {},
            complete: (res) => {
                console.log(res.data);
                typeof cb == 'function' && cb();
            }
        })
    },

    //领取红包
    getRedpaper(e) {
        var that = this;

        const Id = e.currentTarget.dataset.id;
        const Days = e.currentTarget.dataset.days;
        const Received = e.currentTarget.dataset.received;
        const IsReceive = e.currentTarget.dataset.isreceive;

        if (Days != 3 && Days != 7 || Received || IsReceive == 1) {
            return
        }

        app.aldstat.sendEvent('我的-口语-点击领取红包', { '第几天': Days });
        mta.Event.stat("my_spoken_clickGetRedpaper", { whatday: Days });

        var animation = wx.createAnimation({
            transformOrigin: '50% 50%',
            duration: 200,
            timingFunction: 'ease',
            delay: 0
        })

        // that.animation = animation;

        animation.scale(0, 0).step();

        that.setData({
            animationRedPaper: animation.export(),
            clickId: Id,
            clickDays: Days,
            hidemodal: false
        })

        setTimeout(() => {
            animation.scale(1.2, 1.2).step().scale(0.9, 0.9).step().scale(1, 1).step();
            that.setData({
                animationRedPaper: animation.export()
            })
        }, 100);

    },

    tapPushLogin: function(event) {

        app.aldstat.sendEvent('我的-未登录-点击登录');
        mta.Event.stat("my_notlogin_clicklogin", {});

        wx.navigateTo({
            url: `/${paths.login}`,
        })
    },

    tapPushRegist: function(event) {
        wx.navigateTo({
            url: `/${paths.regist}`,
        })
    },

    // 退出登录
    quitLogin: function(event) {

        var self = this;

        app.aldstat.sendEvent('我的-已登录-点击退出登录');
        mta.Event.stat("my_loggedin_exitlogon", {});

        //清除登录用户信息 
        wx.setStorage({
            key: 'loginStatus',
            data: false,
        })
        app.globalData.loginStatus = false
        self.setData({
            loginStatus: false,
            LearningDays: "0",
            PracticeCounts: "0",
            PointPraiseCounts: "0"
        })
    },

    //选择日期
    bindDateChange: function(event) {
        var self = this;

        app.aldstat.sendEvent('我的-已登录-点击选择日期');
        mta.Event.stat("my_loggedin_clickselectdate", {});

        self.setData({
            dateTime: event.detail.value,
        })

        //获取指定日期数据
        var dataDic = {
            OpenId: app.globalData.openId,
            DateTime: self.data.dateTime,
        };

        self.requestRecordData(dataDic)
    },


    aldClickRecord: function() {
        app.aldstat.sendEvent('我的-已登录-点击查看更多练习记录');
        mta.Event.stat("my_loggedin_clickseemore", {});
    },

    //获取录音数据
    requestRecordData: function(dataDic, cb) {
        var self = this

        api.methodGetUserLearningRecords({
            dataDic,
            success: (res) => {
                console.log(res);
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    //刷新当前界面数据
                    self.setData({
                        LearningDays: res.data.data.LearningDays,
                        PracticeCounts: res.data.data.PlayTimes,
                        PointPraiseCounts: res.data.data.PointPraiseCounts,
                        recordList: res.data.data.LearningRecordList,
                    });

                    console.log(self.data.recordList)
                }
            },
            fail: (res) => {},
            complete: (res) => {
                console.log(res.data);
                typeof cb == 'function' && cb();
            }
        });
    },

    //去下一页
    gotoNext: function(e) {
        var that = this;

        var path = e.currentTarget.dataset.path;
        switch (path) {
            case 'myAccount':
                app.aldstat.sendEvent('我的-点击我的账户');
                mta.Event.stat("my_clickmyaccount", {});
                break;
            case 'practice':
                app.aldstat.sendEvent('我的-点击练习记录');
                mta.Event.stat("my_clickpractice", {});
                break;
            case 'pkRecord':
                app.aldstat.sendEvent('我的-点击pk记录');
                mta.Event.stat("my_clickpkrecord", {});
                break;
            case 'set':
                app.aldstat.sendEvent('我的-点击设置');
                mta.Event.stat("my_clickset", {});
                break;
        }
        console.log('去下一页')
        wx.navigateTo({
            url: `/${paths[path]}`
        })
    },
    //打开红包
    openRedPaper(e) {
        var that = this;

        app.aldstat.sendEvent('我的-点击打开红包');
        mta.Event.stat("my_clickopenRedPaper", {});

        const Id = e.currentTarget.dataset.id;
        const Days = e.currentTarget.dataset.days;
        var Money = 0;
        console.log('id', Id, 'Days', Days);

        //执行翻转动画
        var animation = wx.createAnimation({
            transformOrigin: "50% 50%",
            duration: 3000,
            timingFunction: "ease",
            delay: 0
        })
        that.animation = animation
        animation.rotateY(1440).step()
        that.setData({
            animationData: animation.export(),
            openRedPaper: true
        })

        //调用获取红包接口
        var dataDic = {
            OpenId: app.globalData.openId,
            Days: Days,
            SID: Id
        }
        api.methodSignReceiveRedEnvelopes({
            dataDic,
            success: (res) => {
                console.log('领取红包成功', res)
                if (res.data.code != 0) {
                    wx.showModal({
                        title: '温馨提示',
                        showCancel: false,
                        content: res.data.msg,
                    })
                    return;
                } else {
                    const RedAmount = res.data.data.RedAmount; //获得的红包
                    Money = RedAmount ? RedAmount : 0;
                    that.setData({
                        clickId: Id,
                        Money: Money,
                        hidemodal: false
                    })
                }
            },
            fail: (err) => {
                console.log('领取红包失败', err)
            },
            complete: (res) => {

            }
        })

        //将红包设置为已领取
        var ContinueSignData = that.data.ContinueSignData;
        for (let i = 0; i < ContinueSignData.length; i++) {
            var ele = ContinueSignData[i];
            if (ele.Id == Id) {
                var isReceived = 'ContinueSignData[' + i + '].isReceived'
                that.setData({
                        [isReceived]: true
                    })
                    // ele.isReceived = true
            }
        }

        setTimeout(() => {
            that.setData({
                hidemodal: true,
                animationData: null,
                openRedPaper: false
            })
            animation = that.animation;
            animation.rotateY(0).step()
            that.setData({
                animationData: animation.export(),
            })
            wx.navigateTo({
                url: `/${paths.redPaper}?title=签到红包&Money=${that.data.Money}`
            })
        }, 3500);
    },
    cancel() {
        var that = this;

        app.aldstat.sendEvent('我的-点击关闭红包');
        mta.Event.stat("my_clickcancelRedPaper", {});

        that.runAnimate(function(obj) {
            obj.scale(0, 0).step();
        })

        setTimeout(() => {
            that.setData({
                hidemodal: true
            })
        }, 300);
    },
    runAnimate: function(action) {
        var that = this;

        var animation = wx.createAnimation({
            transformOrigin: '50% 50%',
            duration: 200,
            timingFunction: 'ease',
            delay: 0
        })

        // that.animation = animation;

        typeof action == 'function' && action(animation)

        that.setData({
            animationRedPaper: animation.export()
        })

    },


})